class HttpClient {
  constructor(baseURL = '') {
    this.baseURL = baseURL;
  }

  async request(url, options = {}) {
    const config = {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
      ...options,
    };

    // 添加JWT token到请求头（除了登录接口）
    const token = localStorage.getItem('jwt_token');
    if (token && url !== '/api/auth/login') {
      config.headers.Authorization = `Bearer ${token}`;
    }

    try {
      const response = await fetch(this.baseURL + url, config);
      const result = await response.json();

      // 检查是否有新的token
      const newToken = response.headers.get('X-New-Token');
      if (newToken) {
        localStorage.setItem('jwt_token', newToken);
      }

      // 特殊处理登录接口
      if (url === '/auth/login') {
        if (result.code === 0) {
          return result;
        } else {
          this.handleError(result.message);
          return Promise.reject(new Error(result.message));
        }
      }

      // 统一处理认证失败
      if (result.code === 401) {
        this.handleAuthError(result.message);
        return Promise.reject(new Error(result.message));
      }

      // 统一处理其他错误
      if (result.code !== 0) {
        this.handleError(result.message);
        return Promise.reject(new Error(result.message));
      }

      return result.data;
    } catch (error) {
      this.handleError('网络请求失败');
      throw error;
    }
  }

  handleAuthError(message) {
    // 清除本地存储的token
    localStorage.removeItem('jwt_token');
    
    // 显示错误提示
    alert(message || '登录已过期，请重新登录');
    
    // 引导用户到登录页面
    setTimeout(() => {
      window.location.href = '/login';
    }, 1500);
  }

  handleError(message) {
    console.error('请求错误:', message);
    alert(message || '操作失败');
  }

  get(url, options) {
    return this.request(url, { method: 'GET', ...options });
  }

  post(url, data, options) {
    return this.request(url, {
      method: 'POST',
      body: JSON.stringify(data),
      ...options,
    });
  }

  put(url, data, options) {
    return this.request(url, {
      method: 'PUT',
      body: JSON.stringify(data),
      ...options,
    });
  }

  delete(url, options) {
    return this.request(url, { method: 'DELETE', ...options });
  }
}

// 创建全局实例
const httpClient = new HttpClient('/api');